/*
    根据目录结构生成树形路由
    注意children里的path不需要/开头
    每个路由目录下都要有一个index.vue，可以只有一个router-view组件
*/
import { RouteRecordRaw } from 'vue-router'
const modulesFiles = import.meta.globEager('../pages/**/index.vue')

const routeNameMap = {}
const routes:RouteRecordRaw[] = []

for (const path in modulesFiles) {
  const keyArr = path.split('/').slice(2, -1)

  /* 获取路由名 */
  const routeName = modulesFiles[ path ].default.name || keyArr.join('')

  /* 重名校验 */
  if (routeNameMap[ routeName ]) {
    console.error('路由名重复', routeName)
  } else {
    routeNameMap[ routeName ] = 1
  }

  const computedRoute = (arr:string[], routes:any[]) => {
    const routePath = arr.map(item => item.replace(/./, (str) => str.toLowerCase())).join('/')

    if (arr.length === 1) {
      routes.push({
        path: routePath,
        name: routeName,
        component: modulesFiles[ path ].default,
        children: [],
        mkdir: arr[ 0 ],
        ...modulesFiles[ path ].default.route
      })
    } else {
      console.log(routes)
      const routeItem = routes.find(item => item.mkdir === arr[ 0 ])
      routeItem && computedRoute(arr.slice(1), routeItem.children)
    }
  }
  computedRoute(keyArr, routes)
}

/* 最外层的path需要加/ */
routes.forEach(item => {
  item.path = '/' + item.path
})

console.log(routes)
export default routes
